<template>
  <div class="category">
    <h1>{{ id ? "编辑" : "新建" }}物品</h1>
    <el-form label-width="120px" v-model="form" @submit.native.prevent="save">
      <el-form-item label="物品名称">
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <el-form-item label="图标">
        <el-upload
          class="avatar-uploader"
          :action="$http.defaults.baseURL + '/upload'"
          :headers="getAuthHeaders()"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="form.icon" :src="form.icon" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
/* eslint-disable */
export default {
  name: "EquipListAddEdit",
  props: {
    id: {},
  },
  data() {
    return {
      form: {
        name: "", // 名称
        icon: "", // 图标
      },
    };
  },
  created() {
    this.id && this.edit(); // 判断是否有id,有则执行后面的方法
    this.getParentOptions();
  },
  mounted() {},
  methods: {
    // 获得分类列表
    save() {
      let res;
      if (this.id) {
        // 如果存在id，则调用编辑的接口
        res = this.$http.put(`rest/equip/${this.id}`, this.form); // 调用这个接口
      } else {
        res = this.$http.post("rest/equip", this.form); // 调用这个接口
      }
      this.$router.push("/equip/list"); // 路由跳转
      this.$message({
        type: "success",
        message: "保存成功！！！",
      });
    },
    // 获得详情
    async edit() {
      const res = await this.$http.get(`rest/equip/${this.id}`); // 调用接口
      this.form = res.data; // 将查询到的数据返回到页面
    },
    // 获得详情
    async getParentOptions() {
      const res = await this.$http.get(`rest/equip`); // 调用接口
      this.parentOptions = res.data; // 将查询到的数据返回到页面
    },
    handleAvatarSuccess(res, file) {
      this.form.icon = res.url; /*  */
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
};
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
